/*
 * Copyright (C) 2017 Lambour Sebastien
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.breizhbeans.itm4l.service

import io.vertx.groovy.core.MultiMap
import io.vertx.groovy.core.Vertx
import org.breizhbeans.itm4l.exception.NotFoundException

class ServiceRequest {

  def replyHandler
  def errorHandler
  Vertx vertx
  String service

  public ServiceRequest(Vertx vertx) {
    this.vertx = vertx
  }

  public ServiceRequest replyHandler(Closure handler) {
    replyHandler = handler
    this
  }

  public ServiceRequest errorHandler(Closure handler) {
    errorHandler = handler
    this
  }

  public def callService(AbstractService abstractService,  def request, MultiMap headers) {
    // get the service name to execute
    service = headers.get("SERVICE")

    def serviceClosure = abstractService.services.get(service)

    if (null == serviceClosure) {
      throw new NotFoundException(service)
    }

    return serviceClosure.call(this, request )
  }
}
